package com.atguigu.shangrongbao.core.controller.admin;


import com.atguigu.common.result.R;
import com.atguigu.shangrongbao.core.pojo.dto.DictListDto;
import com.atguigu.shangrongbao.core.pojo.dto.ExcelDictDto;
import com.atguigu.shangrongbao.core.pojo.entity.Dict;
import com.atguigu.shangrongbao.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Api(tags = "数据字典")
@RestController
@RequestMapping("/admin/core/dict")
public class AdminDictController {

    //字典service
    @Autowired
    DictService dictService;

    @Autowired
    RedisTemplate redisTemplate;

    @ApiOperation("获取所有字典信息")
    @GetMapping("/listByParentId/{id}")
    public R listByParent(@PathVariable("id") Long id){
        // Assert.isTrue();
        //首先查询redis中是否存在数据
        /**
         * 提高查询效率
         *    使用Redis存储数据，查询的时候如果Redis存在数据则直接返回这个数据
         *    如果不存在，存入数据
         */

        try {
        //    传入的是父集id,所以存入的时候可以根据父集ID进行存入
           List<Dict> dictList = (List<Dict>)redisTemplate.opsForValue().get("core.dictList."+id);
           log.info("redis获取数据:{}", dictList);
           if(dictList != null){
               return R.ok().put("data", dictList);
           }

        }catch (Exception e){
            log.error("redis获取数据时服务异常：{}", e.getStackTrace());

        }
        List<DictListDto> allDict = dictService.getAllDict(id);

        try {
        //    存入数据
            redisTemplate.opsForValue().set("core.dictList."+id, allDict);
            log.info("redis存入数据:{}", allDict);
        }catch (Exception e){
            log.info("redis设置数据时服务异常：{}", e.getStackTrace());
        }
        return  R.ok().put("data", allDict);
    }
}
